import React,{useCallback, useEffect} from 'react';
import {Text, View, StyleSheet, Image, ScrollView, TouchableOpacity} from 'react-native';
import Container from '../../components/Container';
import screen from '../../utils/screen';
import Images from '../../images/images';
import DeviceListItem from '../../components/deviceListItem';
import {useAppStore} from '../../store/useAppStore';
import BleUtil from '../../utils/bleUtil';
import {useNavigation, useRoute} from '@react-navigation/native';
import {useLoading} from '../../components/loading/useLoading';
import {useToast} from '../../components/toast/useToast';
import {useDialog} from '../../components/dialog/useDialog';
import {useModal} from '../../components/useModal';


const DeviceManage = ()=>{

    const navigation = useNavigation()
    const  loading = useLoading()
    const toast = useToast()
    const dialog = useDialog()
    const modal = useModal()
    const route = useRoute()
    const {appState:{deviceList,currentDevice,battery,bluetoothEnable},updateAppState} = useAppStore()

    console.log('Device manager');

    useEffect(()=>{

        navigation.setOptions({
            headerRight:()=>(
                <TouchableOpacity
                    style={{paddingRight:screen.PIXEL_30}}
                    onPress={()=>{

                        navigation.navigate('AddDevice')
                    }}
                >
                    <Image source={Images.add} style={{width:screen.PIXEL_50,height:screen.PIXEL_50}}/>
                </TouchableOpacity>
            ),
        })

    },[])

    const connect = (device)=>{

        BleUtil.connectAndPrepare(device.id).then((info)=>{
            updateAppState({
                currentDevice: device
            })

            loading.hide()
        }).catch(error=>{
            loading.hide()
            let message = error.error === 'timeout' ? '连接超时' : '连接失败'
            toast.show(message)
        })

    }




    const onConnect = (device)=>{
        if(!bluetoothEnable){
            toast.show('请打开蓝牙')
            return
        }
        //如果有连接设备，先断开连接
        console.log('currentDevice',currentDevice);
        if(currentDevice){
            dialog.alertConfirm('连接新设备需要先断开当前连接',()=>{
                loading.show('连接中')
                BleUtil.disconnect(currentDevice.id).then(res=>{
                    console.log('断开连接了：',res)
                    // updateAppState({currentDevice: null,battery:0})
                    connect(device)
                })
            })

        }else{
            loading.show('连接中')
            connect(device)
        }

    }
    const onDisConnect = ()=>{

        //如果有连接设备，先断开连接
        console.log('currentDevice',currentDevice);
        if(currentDevice){

            dialog.alertConfirm('断开当前蓝牙连接?',()=>{
                loading.show('断开连接中')
                BleUtil.disconnect(currentDevice.id).then(res=>{
                    console.log('断开连接了：',res)
                    updateAppState({currentDevice: null,battery:0})
                    loading.hide()
                })
            })

        }else{

        }

    }


    return (
        <Container style={styles.container}>
            <ScrollView
                contentContainerStyle={{paddingHorizontal:screen.PIXEL_30}}
            >
                {
                    deviceList.map((item,index)=>{
                        const isConnect = currentDevice && (currentDevice.id === item.id)

                        return (
                            <DeviceListItem
                                key={index} data={item}
                                isConnect={isConnect}
                                battery={battery}
                                onConnect={()=>{
                                    if(isConnect){
                                        onDisConnect()
                                    }else{
                                        onConnect(item)
                                    }

                                }}

                            />
                        )
                    })
                }
            </ScrollView>
        </Container>
    )
}
export default DeviceManage
const styles = StyleSheet.create({
    container:{

    }

})
